﻿using System;
using System.Collections.Generic;
using nRoute.Internal;

namespace nRoute.ViewServices
{
    internal static class ViewServicesInstancesManager
    {
        private readonly static Object _lock = new Object();
        private static readonly Dictionary<Type, Object> _instances;

        static ViewServicesInstancesManager()
        {
            _instances = new Dictionary<Type, object>();
        }

        public static void RegisterInstance(Type viewServiceType, object serviceInstance)
        {
            Guard.ArgumentNotNull(viewServiceType, "viewServiceType");
            Guard.ArgumentNotNull(serviceInstance, "serviceInstance");
            
            lock (_lock)
            {
                if (_instances.ContainsKey(viewServiceType))
                {
                    _instances[viewServiceType] = serviceInstance;
                }
                else
                {
                    _instances.Add(viewServiceType, serviceInstance);
                }
            }
        }

        public static void UnregisterInstance(Type viewServiceType, object serviceInstance)
        {
            Guard.ArgumentNotNull(viewServiceType, "viewServiceType");
            Guard.ArgumentNotNull(serviceInstance, "serviceInstance");
            
            lock (_lock)
            {
                Object _instance = null;
                if (_instances.TryGetValue(viewServiceType, out _instance))
                {
                    if (object.ReferenceEquals(serviceInstance, _instance))
                    {
                        _instance = null;
                    }
                }
            }
        }

        public static Object GetRegisteredInstance(Type viewServiceType)
        {
            lock (_lock)
            {
                Object _instance = null;
                return (_instances.TryGetValue(viewServiceType, out _instance)) ? _instance
		 : null;
            }
        }
    }
}
